const axios = require('axios')
const sign = require('./sign/b/index');

async function getList({ mid, pn = 1, ps = 30, order = 'pubdate' }) {

  const baseUrl = "https://api.bilibili.com/x/space/wbi/arc/search"
  const data = {
    mid,
    ps,
    tid: 0,
    pn,
    keyword: '',
    order,
    platform: 'web',
    web_location: 1550101,
    order_avoided: true,
  }

  const params = sign(data)


  return axios({
    url: baseUrl,
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    },
    params,
  })

}

const controller = async (ctx) => {

  const { mid } = ctx.request.query

  if (mid) {
    try {
      const res = await getList({ mid })
      if (res.status === 200 && res.data.code === 0) {
        ctx.status = 200
        ctx.body = {
          code: 200,
          msg: 'success',
          data: res.data.data
        }
      } else {
        throw new Error('获取失败')
      }
    } catch (error) {
      console.log(error)
      ctx.status = 500
      ctx.body = {
        code: 500,
        msg: '服务错误',
        error
      }
    }
    return
  }
  ctx.status = 400
  ctx.body = {
    code: 400,
    msg: 'mid不能为空'
  }
}

module.exports = controller